<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList1" @findClicked="findData" />
    <Find :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findData2" :searchImg="false" />

    <el-card style="margin-top: 10px" shadow="always" :body-style="{ padding: '5px' }">
      <div style="display: flex">
        <div style="width: 45%">
          <h1>待出库明细</h1>
          <Table
            @confirmChange="confirmChange1"
            @currentRow="currentRowList"
            class="table1"
            :tableHeader="tableHeader"
            :tableData="table1Data"
            :outTableHeight="60"
            :isLoading="isLoading"
          />
        </div>
        <div style="width: 55%; margin-left: 10px">
          <h1>其他材料出库明细</h1>
          <Table @currentRow="currentRowList2" :tableHeader="tableHeader1" :tableData="table2Data" :outTableHeight="60" :isLoading="isLoading2" />
        </div>
      </div>
      <PageModule :PageData="{ total: total2, buttonS: true }" @pageSizeChange="handleSizeChange2" @pageChange="handleCurrentChange2" />
    </el-card>
    <!-- 选择材料 -->
    <el-drawer v-model="drawer3" :direction="'ttb'" size="small" :with-header="false">
      <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList3" @findClicked="findData1" />
      <div style="width: 60%; margin-top: 13px">
        <Table
          @currentRow1="currentRowList1"
          :isLoading="isLoading1"
          :tableHeader="tableHeader2"
          :tableData="SelectMaterialQueryMehtodsTableDateList.dtos"
          :TableHeight="70"
          :outTableHeight="70"
        />
        <PageModule :PageData="{ total }" @pageSizeChange="handleSizeChangeTk" @pageChange="handleCurrentChangeTk" />
      </div>
    </el-drawer>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import service from '@/utils/request'
import { debounce } from 'lodash'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'OutboundOperation'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import {
  GainClassification,
  GainDeptNmae,
  SelectMaterialQuery,
  type SelectMaterialQueryInterface
} from '@/api/WarehouseDepartment/FactoryStorage/ConsumablesIn'
import {
  OtherMaterialDeliveryDetailsAreDeleted,
  JianBatchProcessingOutOfStorage,
  JianConsumablesToBeRemoved,
  JianQueryDetailsOfOtherMaterialDelivery,
  OutBank,
  DetailsToBeQueried,
  JianDetailsToBeReleasedAdded,
  JianDetailsToBeQueried
} from '@/api/WarehouseDepartment/FactoryStorage/ConsumablesOut'
import type {
  BatchProcessingOutOfStorageParms,
  QueryDetailsOfOtherMaterialDeliveryParms
} from '@/api/WarehouseDepartment/FactoryStorage/ConsumablesOut'
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
const formList1 = ref([
  {
    type: 'button',
    checkboxLabel: '选择材料'
  },
  {
    type: 'dateSingle',
    dateLabel: '出库日期',
    dateValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '部门',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '出库原因',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'button',
    checkboxLabel: '出库批处理'
  },
  {
    type: 'button',
    checkboxLabel: '打印'
  }
]) as any
const formList2 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入出库单号',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '出库原因',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '部门',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '出库日期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '删除待出库明细'
  },
  {
    type: 'button',
    checkboxLabel: '其他材料出库明细删除'
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
]) as any
const formList3 = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '分类',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '材料名称',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
]) as any

// 其他材料出库明细删除
const currentRow2 = ref({})
const currentRowList2 = (row: any) => {
  currentRow2.value = JSON.parse(JSON.stringify(row))
  const { mtlNo, slipNo } = row
  mtlNoList1.value = mtlNo
  slipNoList1.value = slipNo
}
const mtlNoList1 = ref('')
const slipNoList1 = ref('')

const handleCloseMateriaLKlc5 = (_done?: () => void) => {}

// 出库批处理
const BatchProcessingOutOfStorageMethodsParms = ref<BatchProcessingOutOfStorageParms>({
  deptName: '',
  deptNo: '',
  mtlNo: '',
  sendNo: '',
  slipDate: '',
  slipReason: '',
  sysDate: '',
  vendorName: '',
  vendorNo: ''
})

const BatchProcessingOutOfStorageMethods = async () => {
  const result = await JianBatchProcessingOutOfStorage({
    ...BatchProcessingOutOfStorageMethodsParms.value,
    list: table1Data.value
  })
  if (result.code === 200) {
    getTable1List()
    getTableList2()
    JMessage.success(result.message)
  } else {
    getTable1List()
    getTableList2()
    JMessage.error(result.message)
  }
}

// 待出库明细修改
const confirmChange1 = async (row: any) => {
  row.remark === null ? (row.remark = '') : row.remark
  row.qty === null ? (row.qty = null) : row.qty
  console.log(row)
  const result = await LoginWork.post<any, any>(`/product/sdmaterial/updatePcSlipTemp`, {
    amt: '',
    companyId: '',
    flag: '',
    item: '',
    lotNo: '',
    mtlColor: '',
    mtlName: '',
    mtlNo: row.mtlNo,
    mtlSpec: row.mtlSpec,
    mtlUnit: '',
    price: '',
    purNo: '',
    qty: row.qty,
    remark: row.remark,
    slipType: '',
    stkQty: '',
    stockNo: '',
    sysDate: '',
    sysUser: '',
    vendorName: '',
    vendorNo: ''
  })
  if (result.code === 200) {
    getTable1List()
    JMessage.success(result.message)
  } else {
    getTable1List()
    JMessage.error(result.message)
  }
}

const currentRowList = (row: any) => {
  const { mtlNo } = row
  ConsumablesToBeRemovedMehtodsParms.value = mtlNo
  BatchProcessingOutOfStorageMethodsParms.value.mtlNo = mtlNo
}

const ConsumablesToBeRemovedMehtodsParms = ref('')

const handleCloseMateriaLKlc3 = (_done?: () => void) => {}

// 其他材料出库明细查询
const QueryDetailsOfOtherMaterialDeliveryMethodsParms = ref<QueryDetailsOfOtherMaterialDeliveryParms>({
  lotNo: '',
  mtlName: '',
  sendNo: '',
  slipDateEnd: '',
  slipDateStart: '',
  slipNo: '',
  slipReason: '',
  sysDateEnd: '',
  sysDateStart: '',
  vendorNo: ''
}) as any

const table2Data = ref<any>([])
// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
const isLoading2 = ref(true)
const getTableList2 = async () => {
  isLoading2.value = true
  const result = await service.post<any, any>('/product/sdmaterial/pcSlipDetailOutList', {
    ...QueryDetailsOfOtherMaterialDeliveryMethodsParms.value,
    pageNum: currentPage2.value,
    pageSize: pageSize2.value
  })
  table2Data.value = result.list
  total2.value = result.total
  isLoading2.value = false
}

const findData = (count: string) => {
  if (count === '选择材料') {
    SelectMaterialQueryMehtods()
    drawer3.value = true
  }
  if (count === '置空') {
    formList1.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (count === '出库批处理') {
    if (
      BatchProcessingOutOfStorageMethodsParms.value.deptName === '' ||
      BatchProcessingOutOfStorageMethodsParms.value.slipReason === '' ||
      BatchProcessingOutOfStorageMethodsParms.value.slipDate === ''
    ) {
      JMessage.warning('输入数据不完善')
    } else {
      BatchProcessingOutOfStorageMethods()
    }
  }
}
const findData2 = (count: string) => {
  if (count === '置空') {
    formList2.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (count === '删除待出库明细') {
    if (ConsumablesToBeRemovedMehtodsParms.value === '') {
      JMessage.warning('请选择需要删除的数据')
    } else {
      ElMessageBox.confirm('确认要删除数据吗?')
        .then(async () => {
          const result = await JianConsumablesToBeRemoved(ConsumablesToBeRemovedMehtodsParms.value)
          if (result.code === 200) {
            JMessage.success(result.message)
          } else {
            JMessage.error(result.message)
          }
          getTable1List()
        })
        .catch(() => {})
    }
  }
  if (count === '其他材料出库明细删除') {
    if (mtlNoList1.value === '' || slipNoList1.value === '') {
      JMessage.warning('请选择需要删除的数据')
    } else {
      ElMessageBox.confirm('确认要删除数据吗?')
        .then(async () => {
          const reuslt = (await LoginWork.post('/product/sdmaterial/deletePcSlipDetailPartO', currentRow2.value)) as any
          if (reuslt.code === 200) {
            JMessage.success(reuslt.message)
          } else {
            JMessage.error(reuslt.message)
          }
          getTableList2()
        })
        .catch(() => {})
    }
  }
}

// 原因
const OutBankMehotds = async () => {
  const result = await OutBank()
  formList1.value[3].selectOptions = EvaluatesTheArrayReturnValue(result)
  formList2.value[1].selectOptions = EvaluatesTheArrayReturnValue(result)
}

// 部门
const GainDeptNmaeMethods = async () => {
  let NewArray = []
  const result = await GainDeptNmae()
  NewArray = result.reduce((arr: any, item: any) => {
    if (item.deptName && item.deptNo) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.deptNo + ' ' + item.deptName)
    }
    return arr
  }, [])
  formList1.value[2].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
  formList2.value[3].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
}

// 待出明细查询
const table1Data = ref([]) as any
const isLoading = ref(true)
const getTable1List = async () => {
  isLoading.value = true
  const res = (await service.get<any, any>(`/product/sdmaterial/pcSlipTempPartOutList`)) as any
  table1Data.value = res.map((item: any) => {
    item.change = 'Y'
    return item
  })
  isLoading.value = false
}

// 待出明细新增
const currentRowList1 = async (row: any) => {
  const { mtlNo } = row
  DetailsToBeReleasedAddedMethodsParms.value = mtlNo
  const result = await JianDetailsToBeReleasedAdded(DetailsToBeReleasedAddedMethodsParms.value)
  if (result.code === 200) {
    JMessage.success(result.message)
    getTable1List()
  } else {
    JMessage.error(result.message)
    getTable1List()
  }
}

const DetailsToBeReleasedAddedMethodsParms = ref('')

// 获取分类
const clearFormList = () => {
  formList2.value.forEach((item: any) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
    if (item.type === 'select') {
      item.selectValue = ''
    }
  })
}

const findData1 = (row: any) => {
  if (row === '置空') {
    clearFormList()
  }
}

const EvaluatesTheArrayReturnValue = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      optionKey: index,
      optionValue: item,
      optionLabel: item
    }
  })
}

const GainClassificationMehtods = async () => {
  let NewArray = []
  const result = await GainClassification()
  NewArray = result.reduce((arr: any, item: any) => {
    if (item.typeNo && item.typeName) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.typeNo + ' ' + item.typeName)
    }
    return arr
  }, [])
  formList2.value[0].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
}

const SelectMaterialQueryMehtodsTableDateList = ref<SelectMaterialQueryInterface>({
  dtos: []
})

const SelectMaterialQueryMehtodsParms = ref({
  pageNum: 1,
  pageSize: 40
})

const SelectMaterialQueryMehtodsParmsList = ref({
  mtlName: '',
  typeNo: '',
  typeName: ''
}) as any

const SelectMaterialQueryMehtods = async () => {
  isLoading1.value = true
  const result = await service.post<any, any>(
    `/product/sdmaterial/outMaterialList?typeNo=${SelectMaterialQueryMehtodsParmsList.value.typeNo}&typeName=${SelectMaterialQueryMehtodsParmsList.value.typeName}&mtlName=${SelectMaterialQueryMehtodsParmsList.value.mtlName}&pageNum=${SelectMaterialQueryMehtodsParms.value.pageNum}&pageSize=${SelectMaterialQueryMehtodsParms.value.pageSize}`
  )

  // const result = await SelectMaterialQuery(SelectMaterialQueryMehtodsParmsList.value.mtlName, SelectMaterialQueryMehtodsParmsList.value.type, SelectMaterialQueryMehtodsParms.value)
  SelectMaterialQueryMehtodsTableDateList.value.dtos = result.list
  total.value = result.total
  isLoading1.value = false
}

const drawer3 = ref(false)

const isLoading1 = ref(false)

const total = ref(0)

const handleSizeChangeTk = (val: number) => {
  SelectMaterialQueryMehtodsParms.value.pageSize = val
  SelectMaterialQueryMehtods()
}

const handleCurrentChangeTk = (val: number) => {
  SelectMaterialQueryMehtodsParms.value.pageNum = val
  SelectMaterialQueryMehtods()
}

onMounted(() => {
  getTable1List()

  GainDeptNmaeMethods()

  OutBankMehotds()

  getTableList2()
})

// 表格数据
const tableHeader = ref([
  {
    label: '物料编码',
    prop: 'mtlNo',
    change: true
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    label: '库存量',
    prop: 'stkQty',
    change: true
  },
  {
    label: '数量',
    prop: 'qty'
  },
  {
    label: '备注',
    prop: 'remark'
  }
])

const tableHeader1 = ref([
  {
    label: '出库单号',
    prop: 'slipNo'
  },
  {
    label: '出库日期',
    prop: 'slipDate'
  },
  {
    label: '出库部门',
    prop: 'slipReason'
  },
  {
    label: '出库原因',
    prop: 'slipReason'
  },
  {
    label: '材料颜色',
    prop: 'mtlColor'
  },
  {
    label: '材料名称',
    prop: 'mtlName'
  },
  {
    label: '规格',
    prop: 'mtlSpec'
  },
  {
    label: '单位',
    prop: 'mtlUnit'
  },
  {
    label: '数量',
    prop: 'qty'
  },
  {
    label: '物料编号',
    prop: 'mtlNo'
  },
  {
    label: '仓管员',
    prop: 'sysUser'
  },
  {
    label: '备注',
    prop: 'remark'
  }
])

const tableHeader2 = ref([
  {
    label: '物料编码',
    prop: 'mtlNo'
  },
  {
    label: '分类名称',
    prop: 'typeName'
  },
  {
    label: '材料名称',
    prop: 'mtlName'
  },
  {
    label: '规格',
    prop: 'mtlSpec'
  },
  {
    label: '颜色',
    prop: 'mtlColor'
  },
  {
    label: '单位',
    prop: 'mtlUnit'
  },
  {
    label: '库存量',
    prop: 'stkQty'
  }
])
watch(formList3.value, () => {
  SelectMaterialQueryMehtodsParmsList.value.mtlName = formList3.value[1].inputValue
  SelectMaterialQueryMehtodsParmsList.value.typeNo = formList3.value[0].selectValue.split(' ')[0] || ''
  SelectMaterialQueryMehtodsParmsList.value.typeName = formList3.value[0].selectValue.split(' ')[1] || ''
  SelectMaterialQueryMehtods()
})
onMounted(() => {
  GainClassificationMehtods()
})

watch(formList2.value, () => {
  QueryDetailsOfOtherMaterialDeliveryMethodsParms.value.slipNo = formList2.value[0].inputValue
  QueryDetailsOfOtherMaterialDeliveryMethodsParms.value.slipReason = formList2.value[1].selectValue
  QueryDetailsOfOtherMaterialDeliveryMethodsParms.value.mtlName = formList2.value[2].inputValue
  QueryDetailsOfOtherMaterialDeliveryMethodsParms.value.vendorNo = formList2.value[3].selectValue ? formList2.value[3].selectValue.split(' ')[0] : ''
  QueryDetailsOfOtherMaterialDeliveryMethodsParms.value.slipDateEnd = formList2.value[4].dateValue ? formList2.value[4].dateValue[1] : ''
  QueryDetailsOfOtherMaterialDeliveryMethodsParms.value.slipDateStart = formList2.value[4].dateValue ? formList2.value[4].dateValue[0] : ''
  getTableList2()
})
watch(formList1.value, () => {
  BatchProcessingOutOfStorageMethodsParms.value.slipDate = formList1.value[1].dateValue
  BatchProcessingOutOfStorageMethodsParms.value.deptName = formList1.value[2].selectValue ? formList1.value[2].selectValue.split(' ')[1] : ''
  BatchProcessingOutOfStorageMethodsParms.value.deptNo = formList1.value[2].selectValue ? formList1.value[2].selectValue.split(' ')[0] : ''
  BatchProcessingOutOfStorageMethodsParms.value.slipReason = formList1.value[3].selectValue
})
</script>

<style lang="less" scoped>
h1 {
  font-size: 16px;
}

.table1 {
  :deep(th:nth-child(7)) {
    color: #0000ff !important;
  }

  :deep(th:nth-child(8)) {
    color: #0000ff !important;
  }
}
</style>
